package com.iqiyi.pps.epg.web.webapp.action.auth;

import com.iqiyi.pps.epg.core.dao.base.HibernateUtils;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.exception.ServiceException;
import com.iqiyi.pps.epg.core.model.auth.Authority;
import com.iqiyi.pps.epg.core.model.auth.Role;
import com.iqiyi.pps.epg.core.service.auth.SysRoleManager;
import com.iqiyi.pps.epg.core.service.auth.SysUserManager;
import com.iqiyi.pps.epg.web.utils.Struts2Utils;
import com.iqiyi.pps.epg.web.webapp.action.BaseAction;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 角色管理Action.
 * 
 * 演示不分页的简单管理界面.
 * 
 * @author calvin
 */
@Namespace("/auth/role")
@Scope("prototype")
@Results( { @Result(name = BaseAction.RELOAD, location = "role.action", type = "redirect") })
public class RoleAction extends BaseAction<Role> {

	private static final long serialVersionUID = -4052047494894591406L;

	private SysUserManager sysUserManager;
    @Autowired
    private SysRoleManager sysRoleManager;

	//-- 页面属性 --//
	private Long id;
	private Role entity;
	private List<Role> allRoleList;//角色列表
	private List<Long> checkedAuthIds;//页面中钩选的权限id列表
    private String code;
    private String message;

    private Page<Role> page = new Page<Role>(5);//每页5条记录

    //-- ModelDriven 与 Preparable函数 --//
	public Role getModel() {
		return entity;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = sysUserManager.getRole(id);
		} else {
			entity = new Role();
		}
	}

	//-- CRUD Action 函数 --//
	@Override
    @Action(value = "list")
	public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        //设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }
        page = sysRoleManager.searchRole(page,filters);
        return SUCCESS;
	}

	@Override
    @Action(value = "input")
	public String input() throws Exception {
		checkedAuthIds = entity.getAuthIds();
		return INPUT;
	}

	@Override
    @Action(value = "save")
	public String save() throws Exception {
		//根据页面上的checkbox 整合Role的Authorities Set.
        if(null != checkedAuthIds){
		HibernateUtils.mergeByCheckedIds(entity.getAuthorityList(), checkedAuthIds, Authority.class);
            for(Long id: checkedAuthIds) {
                Authority authorty = sysUserManager.getAuthorty(id);
                if(authorty != null) {
                    entity.getAuthorityList().add(authorty);
                }
            }
        }
        checkedAuthIds = entity.getAuthIds();
		//保存用户并放入成功信息.
        sysRoleManager.saveRole(entity);

		addActionMessage("保存角色成功");
		return INPUT;
	}

	@Override
    @Action(value = "delete")
	public String delete() throws Exception {
        try{
             sysUserManager.deleteRole(id);
		    // addActionMessage("删除角色成功");
             message  = "操作成功";
             code = "A00000";
        }catch (ServiceException e){
            logger.error(e.getMessage(), e);
            code = "A00001";
			addActionMessage(e.getMessage());
            message = "操作失败";
        }

		return "verify";
	}


      /**
	 * 支持使用Jquery.validate Ajax检验角色名是否重复.
	 */
    @Action(value = "check_role_name")
	public String checkRoleName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String newRoleName = request.getParameter("name");
		String oldRoleName = request.getParameter("oldRoleName");

		if (sysUserManager.isRoleNameUnique(newRoleName, oldRoleName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		//因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}
	//-- 页面属性访问函数 --//
	/**
	 * list页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return allRoleList;
	}

	/**
	 * input页面显示所有授权列表.
	 */
	public List<Authority> getAllAuthorityList() {
        List<Authority> authorities = sysUserManager.getAllAuthority();
        Authority auth = null;
        for(Authority authority: authorities) {
            if(authority.getName().equals("AUTHENTICATED")) {
                auth = authority;
            }
        }

        authorities.remove(auth);
		return authorities;
	}

	/**
	 * input页面显示角色拥有的授权.
	 */
	public List<Long> getCheckedAuthIds() {
		return checkedAuthIds;
	}

	/**
	 * input页面提交角色拥有的授权.
	 */
	public void setCheckedAuthIds(List<Long> checkedAuthIds) {
		this.checkedAuthIds = checkedAuthIds;
	}

	@Autowired
	public void setSysUserManager(SysUserManager sysUserManager) {
		this.sysUserManager = sysUserManager;
	}

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SysRoleManager getSysRoleManager() {
        return sysRoleManager;
    }

    public void setSysRoleManager(SysRoleManager sysRoleManager) {
        this.sysRoleManager = sysRoleManager;
    }

    public Role getEntity() {
        return entity;
    }

    public void setEntity(Role entity) {
        this.entity = entity;
    }

    public Page<Role> getPage() {
        return page;
    }

    public void setPage(Page<Role> page) {
        this.page = page;
    }
}